<?php
/**
* 将字符串转换为数组
*
* @param	string	$data	字符串
* @return	array	返回数组格式，如果，data为空，则返回空数组
*/
function string2array($data) {
	if($data == '') return array();
	@eval("\$array = $data;");
	return $array;
}
/**
* 将数组转换为字符串
*
* @param	array	$data		数组
* @param	bool	$isformdata	如果为0，则不使用new_stripslashes处理，可选参数，默认为1
* @return	string	返回字符串，如果，data为空，则返回空
*/
function array2string($data, $isformdata = 1) {
	if($data == '') return '';
	if($isformdata) $data = new_stripslashes($data);
	return addslashes(var_export($data, TRUE));
}

/**
  * 返回经stripslashes处理过的字符串或数组
  * @param $string 需要处理的字符串或数组
  * @return mixed
  */
 function new_stripslashes($string) {
     if(!is_array($string)) return stripslashes($string);
     foreach($string as $key => $val) $string[$key] = new_stripslashes($val);
     return $string;
 }

/**
 * 安全过滤函数
 *
 * @param $string
 * @return string
 */
function safe_replace($string) {
	$string = str_replace('%20','',$string);
	$string = str_replace('%27','',$string);
	$string = str_replace('%2527','',$string);
	$string = str_replace('*','',$string);
	$string = str_replace('"','&quot;',$string);
	$string = str_replace("'",'',$string);
	$string = str_replace('"','',$string);
	$string = str_replace(';','',$string);
	$string = str_replace('<','&lt;',$string);
	$string = str_replace('>','&gt;',$string);
	$string = str_replace("{",'',$string);
	$string = str_replace('}','',$string);
	$string = str_replace('\\','',$string);
	return $string;
}
/**
 * 转义 javascript 代码标记
 *
 * @param $str
 * @return mixed
 */
 function trim_script($str) {
	if(is_array($str)){
		foreach ($str as $key => $val){
			$str[$key] = trim_script($val);
		}
 	}else{
 		$str = preg_replace ( '/\<([\/]?)script([^\>]*?)\>/si', '&lt;\\1script\\2&gt;', $str );
		$str = preg_replace ( '/\<([\/]?)iframe([^\>]*?)\>/si', '&lt;\\1iframe\\2&gt;', $str );
		$str = preg_replace ( '/\<([\/]?)frame([^\>]*?)\>/si', '&lt;\\1frame\\2&gt;', $str );
		$str = preg_replace ( '/]]\>/si', ']] >', $str );
 	}
	return $str;
}
/**
 * 获取当前页面完整URL地址
 */
function get_url() {
	$sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
	$php_self = $_SERVER['PHP_SELF'] ? safe_replace($_SERVER['PHP_SELF']) : safe_replace($_SERVER['SCRIPT_NAME']);
	$path_info = isset($_SERVER['PATH_INFO']) ? safe_replace($_SERVER['PATH_INFO']) : '';
	$relate_url = isset($_SERVER['REQUEST_URI']) ? safe_replace($_SERVER['REQUEST_URI']) : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.safe_replace($_SERVER['QUERY_STRING']) : $path_info);
	return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
}
/**
 * @brief 获取网站根路径
 * @param  string $protocol 协议  默认为http协议，不需要带'://'
 * @return String $baseUrl  网站根路径
 *
 */
function getHost($protocol='http')
{
	$port    = $_SERVER['SERVER_PORT'] == 80 ? '' : ':'.$_SERVER['SERVER_PORT'];
	$host	 = isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '');
	$baseUrl = $protocol.'://'.$host.$port;
	return $baseUrl;
}
/**
 * 数组保存到文件
 * @param string $filename 文件地址
 * @param array	 $arr 保存的数组
 */ 
function array2file($filename, $arr='array()'){
	if(is_array($arr)){
		$con = var_export($arr,true);
	} else{
		$con = $arr;
	}
	$con = "<?php\nreturn $con;\n?>";//\n!defined('IN_MP') && die();\nreturn $con;\n
	write_file($filename, $con);
}

/**
 * 创建多级目录
 * @param string $dirs	多级目录
 * @param int $mode	权限
 */
function mkdirs($dirs, $mode=0775) {
	if(!is_dir($dirs)){
		mkdirs(dirname($dirs), $mode);
		return @mkdir($dirs, $mode);
	}
	return true;
}

function write_file($l1, $l2=''){
	$dir = dirname($l1);
	if(!is_dir($dir)){
		mkdirs($dir);
	}
	return @file_put_contents($l1, $l2);
}

function read_file($l1){
	return @file_get_contents($l1);
}


//获得某天前的最后一秒时间戳
function xtime( $day ){
	$day = intval($day);
	return mktime(23,59,59,date("m"),date("d")-$day,date("y"));
}

// 获取相对目录
function get_base_path( $filename ){
    $base_path = $_SERVER['PHP_SELF'];
    $base_path = substr($base_path,0,strpos($base_path,$filename));
	return $base_path;
}

// 获取相对路径
function get_base_url($baseurl, $url){
	if("#" == $url){
		return "";
	}elseif(FALSE !== stristr($url,"http://")){
		return $url;
	}elseif( "/" == substr($url,0,1) ){
		$tmp = parse_url($baseurl);
		return $tmp["scheme"]."://".$tmp["host"].$url;
	}else{
		$tmp = pathinfo($baseurl);
		return $tmp["dirname"]."/".$url;
	}
}

//输入过滤 同时去除连续空白字符可参考扩展库的remove_xss
function get_replace_input( $str, $rptype = 0 ){
	$str = stripslashes($str);
	$str = htmlspecialchars($str);
	$str = get_replace_nb($str);
	return addslashes($str);
}

//去除换行
function get_replace_nr( $str ){
	$str = str_replace(array("<nr/>","<rr/>"),array("\n","\r"),$str);
	return trim($str);
}

//去除连续空格
function get_replace_nb( $str ){
	$str = str_replace("&nbsp;",' ',$str);
	$str = str_replace("　",' ',$str);
	$str = ereg_replace("[\r\n\t ]{1,}",' ',$str);
	return trim($str);
}

//去除所有标准的HTML代码
function get_replace_html($str, $start=0, $length, $charset="utf-8", $suffix=false){
	return msubstr(eregi_replace('<[^>]+>','',ereg_replace("[\r\n\t ]{1,}",' ',get_replace_nb($str))),$start,$length,$charset,$suffix);
}

//正则提取正文里指定的第几张图片地址
function get_image_in_content($content, $number = 1){
	preg_match_all('/<img(.*?)src="(.*?)(?=")/si',$content,$imgarr);
	preg_match_all('/(?<=src=").*?(?=")/si',implode('" ',$imgarr[0]).'" ',$imgarr);
	$countimg = count($imgarr);
	if($number > $countimg){
		$number = $countimg;
	}
	return $imgarr[0][($number-1)];
}


/**
 * 货币显示
 * @param float $value	价格
 * @param string $type	货币符号
 * @param bool $showSymbol	是否显示货币符号
 */
function currency($value, $type = null, $showSymbol = true)
{
  static $n = null, $symbol = '', $isleft = 1;
  if (!isset($n)) {
    if (!isset($currencies)) {
      $currencies = SiteModel::currencyList();
    }
    if (!isset($default)) {
      $default = C('currency');
    }
    $n = 1;
    if ($default && isset($currencies[$default])) {
      $symbol = $currencies[$default]['symbol'];
      $isleft = $currencies[$default]['isleft'];
      if (isset($type) && isset($currencies[$type])) {
      } else if (isset($_SESSION['currency']) && isset($currencies[$_SESSION['currency']])) {
        $type = $_SESSION['currency'];
      } else {
        $type = false;
      }
      if ($type && $type != $default) {
        $symbol = $currencies[$type]['symbol'];
        $isleft = $currencies[$type]['isleft'];
        $n = $currencies[$default]['exchange'] / $currencies[$type]['exchange'];
      }
    }
  }
  $value /= $n;
  $result = number_format($value, 2, '.', '');
  if($showSymbol){
  	if($isleft){
  		 $result = $symbol . $result;
  	}else{
  		$result = $result. $symbol;
  	}
  }
  return $result;
}

//截取字符串
function strwidth($str, $width, $marker = '...')
{
  return mb_strimwidth($str, 0, $width, $marker, 'UTF8');
}
//定义U函数别名
function url($url='', $vars='', $suffix=true){
	if(empty($url)){
		return (is_ssl()?'https://':'http://').strtolower($_SERVER['HTTP_HOST']) . '/';
	}else{
		return U($url, $vars, $suffix, false, true);
	}
}

  //url特殊符号处理
function generateUrl_un($str) {
    $url = urlencode(preg_replace('/[\.|\/|\?|&|\+|\\\|\'|"|,]+/','-', strtolower(trim($str))));
    $url = str_replace('+', '-', $url);
    $url = str_replace('%', '-', $url);
    $url = str_replace('__', '-', $url);
    $url = str_replace('-.', '-', $url);
    $url = str_replace(' ', '-', $url);
    return $url;
}

  //输入年月，返回当月的开始时间和结束时间
function dateStage($year, $month)
{
	$starttime = strtotime($year.'-'.$month.'-01');
	$endmonth = $month == 12 ? 1 : $month + 1;
	$endyear = $month == 12 ? $year + 1 : $year;
	
	$endtime = strtotime($endyear.'-'.$endmonth.'-01') - 1;
	return array($starttime,$endtime);
}

  //输入两个日期，返回这两个日期之间的所有日期
function getAllDates($start, $end, $dataType){
	$Dates   = array();
	$typeArr = array('year','month','week','day','hour','minute','second');
	if(!in_array($dataType,$typeArr)){
	    return $Dates;
	}
	$dt_start = strtotime($start);
	$dt_end   = strtotime($end);
	while ($dt_start<=$dt_end){
		$Dates[]  = date('Y-m-d H:i:s', $dt_start);
		$dt_start = strtotime('+1 '.$dataType, $dt_start);
	}
	return $Dates;
}
//截取字符串
function cutstr($string, $length, $dot = ' ...',$type=2) {
    $charset="utf-8";

    if(strlen($string) <= $length) {
        return $string;
    }
    if ( $type == 2) {
        $string = strip_tags($string);
        $string = trim($string);
    }
    $string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array('&', '"', '<', '>'), $string);

    $strcut = '';
    if(strtolower($charset) == 'utf-8') {

        $n = $tn = $noc = 0;
        while($n < strlen($string)) {

            $t = ord($string[$n]);
            if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
                $tn = 1; $n++; $noc++;
            } elseif(194 <= $t && $t <= 223) {
                $tn = 2; $n += 2; $noc += 2;
            } elseif(224 <= $t && $t < 239) {
                $tn = 3; $n += 3; $noc += 2;
            } elseif(240 <= $t && $t <= 247) {
                $tn = 4; $n += 4; $noc += 2;
            } elseif(248 <= $t && $t <= 251) {
                $tn = 5; $n += 5; $noc += 2;
            } elseif($t == 252 || $t == 253) {
                $tn = 6; $n += 6; $noc += 2;
            } else {
                $n++;
            }

            if($noc >= $length) {
                break;
            }

        }
        if($noc > $length) {
            $n -= $tn;
        }

        $strcut = substr($string, 0, $n);

    } else {
        for($i = 0; $i < $length; $i++) {
            $strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
        }
    }

    $strcut = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);

    return $strcut.$dot;
}

?>